document.addEventListener('click', event => {
    showWindowWithFavoriteBooks(event);
    closeWindowWithFavoriteBooks(event);
    openBook(event);
})



function openBook(event) {
    const bookCard = event.target.closest('.book-card-favorite');
    if (!bookCard) return;
    
    const bookSlug = bookCard.dataset.nameOfBook;
    const url = document.location.origin + `/book/${bookSlug}`;
    document.location.href = url;
}

function closeWindowWithFavoriteBooks(event) {
    if (event.target.classList.contains('window-with-favorite-books-wrapper')) {
        document.querySelector('.window-with-favorite-books-wrapper').remove();
    }
}

function showWindowWithFavoriteBooks(event) {
    // Показываем окно с избранными книгами

    if (!event.target.classList.contains('favorites')) return;
    event.preventDefault();

    const windowWithFavoriteBooks = getWindowWithFavoriteBooks();
    addData(windowWithFavoriteBooks);
    document.querySelector('.favorites').insertAdjacentElement('beforeend', windowWithFavoriteBooks);


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ


    function addData(windowWithFavoriteBooks) {
        const url = document.location.origin + '/books/?favorites_books=true';
        base.sendAjaxRequest(url, 'GET')
            .then(result => {
                insertData(result, windowWithFavoriteBooks);
            })
    }

    function insertData(data, windowWithFavoriteBooks) {
        const windowWithFavoriteBooksInner = document.createElement('div');
        windowWithFavoriteBooksInner.className = 'window-with-favorite-books-inner';
        books = Object.values(Object.values(data['books']));
        console.log(books)
        for (const book of books) {
            const bookCardFavorite = `
                <div class="book-card-favorite" data-name-of-book="${book.slug}">
                    <div class="image-book-card-favorite">
                        <img src="/${book.image}">
                    </div>
                    <div class="additionally-book-card-favorite">
                        <div class="title-book-card-favorite">
                            ${book.title}
                        </div>
                        <div class="description-book-card-favorite">
                            ${book.description}
                        </div>
                    </div>
                </div>
            `;
            windowWithFavoriteBooksInner.insertAdjacentHTML('beforeend', bookCardFavorite);
        }
        windowWithFavoriteBooks.insertAdjacentElement('beforeend', windowWithFavoriteBooksInner);
    }

    function getWindowWithFavoriteBooks() {
        const windowWithFavoriteBooks = document.createElement('div');
        windowWithFavoriteBooks.className = 'window-with-favorite-books-wrapper';
        return windowWithFavoriteBooks;
    }
}